package com.bz.controller;

import com.bz.db.enties.BusRoomUser;
import com.bz.db.enties.pojo.CommonResult;
import com.bz.db.enties.pojo.GlobalErrorCodeConstants;
import com.bz.model.MessageListO;
import com.bz.response.ErrorCodeEnum;
import com.bz.service.IBusRoomUserService;
import com.bz.service.socket.GroupChatServer;
import com.bz.util.SocketUtil;
import com.bz.util.UuidUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import static com.bz.db.enties.pojo.CommonResult.error;
import static com.bz.db.enties.pojo.CommonResult.success;


@Slf4j
@RestController()
@Validated
public class SocketController {

    @Resource
    private IBusRoomUserService busRoomUserService;
    @Resource
    private GroupChatServer groupChatServer;


    @PostMapping("/socket/createRoom")
    public CommonResult<BusRoomUser> createRoom(@RequestBody BusRoomUser busRoomUser) {
        try {
            BusRoomUser busRoomUser1 = busRoomUserService.createRoom(busRoomUser);
            return success(busRoomUser1);
        } catch (Exception e) {
            log.error("创建房间时发生错误: {}", e.getMessage(), e);
            return error(ErrorCodeEnum.SYSTEM_ERROR.getCode(), "创建房间时发生错误");
        }
    }


    @PostMapping("/socket/getRooms")
    public CommonResult<List<MessageListO>> getRooms(@RequestBody BusRoomUser busRoomUser) {
        try {
            //List<BusRoomUser> busRoomUser1 = busRoomUserService.selectRoomS(busRoomUser);
            List<MessageListO> listOS = groupChatServer.getMessTot(busRoomUser.getUser1());
            return success(listOS);
        } catch (Exception e) {
            log.error("创建房间时发生错误: {}", e.getMessage(), e);
            return error(ErrorCodeEnum.SYSTEM_ERROR.getCode(), "创建房间时发生错误");
        }
    }


    @Value("${app.upload.dir}")
    private String uploadDir;

    @PostMapping("/api/upload")
    public CommonResult<String> upload(@RequestParam("file") MultipartFile file, @RequestParam("userId") String userId) {
        String fileSeparator = File.separator;
        if (file.isEmpty()) {
            return error(ErrorCodeEnum.FILE_ERROR.getCode(), "上传的文件不能为空");
        }
        try {
            // 获取文件存储路径
            Path uploadPath = Paths.get(uploadDir + fileSeparator + userId);
            // 如果目录不存在，则创建目录
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            // 验证文件类型是否合法
            // 获取文件原始名称
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !SocketUtil.isValidFileType(originalFilename)) {
                return error(GlobalErrorCodeConstants.INVALID_FILE_TYPE);
            }
            // 提取文件扩展名
            String fileExtension = "";
            if (originalFilename != null && originalFilename.lastIndexOf('.') > 0) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf('.') + 1);
            }
            // 构建文件存储路径
            String fileName = UuidUtils.uuid() + "." + fileExtension;
            Path filePath = uploadPath.resolve(fileName);
            // 保存文件
            try (InputStream inputStream = file.getInputStream()) {
                Files.copy(inputStream, filePath);
                // 异步生成缩略图
                SocketUtil.generateThumbnailAsync(filePath.toString());
            } catch (Exception e) {
                return error(ErrorCodeEnum.FILE_UPLOAD.getCode(), "文件上传时发生错误: " + e.getMessage());
            }
            return success(userId + fileSeparator + fileName + "_thumb.jpg");
        } catch (IOException e) {
            log.error("文件上传时发生错误: {}", e.getMessage(), e);
            return error(ErrorCodeEnum.SYSTEM_ERROR.getCode(), "文件上传时发生错误");
        }
    }

}
